package com.mzz.upload;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class SftpUploadDesktopApp extends JFrame {
    private static final String[] COLUMN_NAMES = {"IP", "用户名", "密码", "远程路径"};
    private static final Object[][] DATA = {
            {"101.132.169.107", "root", "password1", "/root/java/webapps"},
            {"101.132.169.107", "root", "password2", "/root/www"}
    };

    private JButton uploadButton;
    private JLabel statusLabel;
    private JTable serverTable;

    public SftpUploadDesktopApp() {
        super("SFTP文件上传");

        uploadButton = new JButton("选择文件或文件夹并上传");
        statusLabel = new JLabel();

        serverTable = new JTable(new DefaultTableModel(DATA, COLUMN_NAMES));

        uploadButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int result = fileChooser.showOpenDialog(SftpUploadDesktopApp.this);

                if (result == JFileChooser.APPROVE_OPTION) {
                    File[] selectedFiles = fileChooser.getSelectedFiles();
                    int selectedRow = serverTable.getSelectedRow();

                    if (selectedRow >= 0) {
                        String server = (String) serverTable.getValueAt(selectedRow, 0);
                        String username = (String) serverTable.getValueAt(selectedRow, 1);
                        String password = (String) serverTable.getValueAt(selectedRow, 2);
                        String remotePath = (String) serverTable.getValueAt(selectedRow, 3);

                        uploadFiles(selectedFiles, server, username, password, remotePath);
                    }
                }
            }
        });

        setLayout(new FlowLayout());
        add(uploadButton);
        add(new JScrollPane(serverTable));
        add(statusLabel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 500);
        setVisible(true);
    }

    private void uploadFiles(File[] files, String server, String username, String password, String remotePath) {
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jSch = new JSch();

            // 创建会话
            session = jSch.getSession(username, server, 22);
            session.setPassword(password);

            // 配置会话选项
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接会话
            session.connect();

            // 打开SFTP通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            for (File file : files) {
                if (file.isFile()) {
                    // 上传文件
                    FileInputStream fis = new FileInputStream(file);
                    channelSftp.put(fis, remotePath + "/" + file.getName());
                    fis.close();
                } else if (file.isDirectory()) {
                    // 上传文件夹
                    uploadDirectory(channelSftp, file, remotePath);
                }
            }

            statusLabel.setText("文件上传成功");
        } catch (Exception e) {
            String errorMessage = "文件上传失败：" + e.getMessage();
            statusLabel.setText(errorMessage);
            JOptionPane.showMessageDialog(this, errorMessage, "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            // 关闭SFTP通道和会话
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    private void uploadDirectory(ChannelSftp channelSftp, File directory, String remotePath) throws Exception {
        List<File> fileList = listFiles(directory);
        for (File file : fileList) {
            if (file.isFile()) {
                // 获取相对路径
                String relativePath = file.getAbsolutePath().substring(directory.getAbsolutePath().length());
                if (relativePath.startsWith(File.separator)) {
                    relativePath = relativePath.substring(1);
                }

                // 上传文件
                FileInputStream fis = new FileInputStream(file);
                channelSftp.put(fis, remotePath + "/" + relativePath);
                fis.close();
            }
        }
    }

    private List<File> listFiles(File directory) {
        List<File> fileList = new ArrayList<>();
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    fileList.add(file);
                } else if (file.isDirectory()) {
                    fileList.addAll(listFiles(file));
                }
            }
        }
        return fileList;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new SftpUploadDesktopApp();
            }
        });
    }
}